----------------------------------------------------------------
-- Global Variables
----------------------------------------------------------------
GuildVaultWindow = {}

GuildVaultWindow.vaultDataTable = {}

GuildVaultWindow.SelectedVault = 1
GuildVaultWindow.MAX_SLOTS = 60
GuildVaultWindow.MAX_VAULTS = 4

GuildVaultWindow.VaultSource = {}
GuildVaultWindow.VaultSource[1] = Cursor.SOURCE_GUILD_VAULT1
GuildVaultWindow.VaultSource[2] = Cursor.SOURCE_GUILD_VAULT2
GuildVaultWindow.VaultSource[3] = Cursor.SOURCE_GUILD_VAULT3
GuildVaultWindow.VaultSource[4] = Cursor.SOURCE_GUILD_VAULT4

GuildVaultWindow.TABS_VAULT1		= 1
GuildVaultWindow.TABS_VAULT2		= 2
GuildVaultWindow.TABS_VAULT3		= 3
GuildVaultWindow.TABS_VAULT4		= 4


-- This table contains 4 tables, one for each Guild Vault.
-- Each one of those tables contains an index representing a locked slot. The contents of that index is the memberID that locked the slot.
GuildVaultWindow.vaultDataLockTable = {}
GuildVaultWindow.vaultDataLockTable[GuildVaultWindow.TABS_VAULT1] = {}
GuildVaultWindow.vaultDataLockTable[GuildVaultWindow.TABS_VAULT2] = {}
GuildVaultWindow.vaultDataLockTable[GuildVaultWindow.TABS_VAULT3] = {}
GuildVaultWindow.vaultDataLockTable[GuildVaultWindow.TABS_VAULT4] = {}

GuildVaultWindow.Tabs = {}
GuildVaultWindow.Tabs[ GuildVaultWindow.TABS_VAULT1 ]	= { name="GuildVaultWindowTabsVault1",	label=StringTables.Guild.LABEL_GUILD_VAULT_TAB_VAULT1, tooltipEnabled=StringTables.Guild.TOOLTIP_GUILD_VAULT1_ENABLED, tooltipLocked=StringTables.Guild.TOOLTIP_GUILD_VAULT1_LOCKED, tooltipDisabled=StringTables.Guild.TOOLTIP_GUILD_VAULT_DISABLED }
GuildVaultWindow.Tabs[ GuildVaultWindow.TABS_VAULT2 ]	= { name="GuildVaultWindowTabsVault2",	label=StringTables.Guild.LABEL_GUILD_VAULT_TAB_VAULT2, tooltipEnabled=StringTables.Guild.TOOLTIP_GUILD_VAULT2_ENABLED, tooltipLocked=StringTables.Guild.TOOLTIP_GUILD_VAULT2_LOCKED, tooltipDisabled=StringTables.Guild.TOOLTIP_GUILD_VAULT_DISABLED }
GuildVaultWindow.Tabs[ GuildVaultWindow.TABS_VAULT3 ]	= { name="GuildVaultWindowTabsVault3",	label=StringTables.Guild.LABEL_GUILD_VAULT_TAB_VAULT3, tooltipEnabled=StringTables.Guild.TOOLTIP_GUILD_VAULT3_ENABLED, tooltipLocked=StringTables.Guild.TOOLTIP_GUILD_VAULT3_LOCKED, tooltipDisabled=StringTables.Guild.TOOLTIP_GUILD_VAULT_DISABLED }
GuildVaultWindow.Tabs[ GuildVaultWindow.TABS_VAULT4 ]	= { name="GuildVaultWindowTabsVault4",	label=StringTables.Guild.LABEL_GUILD_VAULT_TAB_VAULT4, tooltipEnabled=StringTables.Guild.TOOLTIP_GUILD_VAULT4_ENABLED, tooltipLocked=StringTables.Guild.TOOLTIP_GUILD_VAULT4_LOCKED, tooltipDisabled=StringTables.Guild.TOOLTIP_GUILD_VAULT_DISABLED }

GuildVaultWindow.UNLOCKS = {}
GuildVaultWindow.UNLOCKS.VAULT1 = 3		-- Guild Vault 1 unlocks at Guild Rank 3
GuildVaultWindow.UNLOCKS.VAULT2 = 11	-- Guild Vault 2 unlocks at Guild Rank 11
GuildVaultWindow.UNLOCKS.VAULT3 = 23	-- Guild Vault 3 unlocks at Guild Rank 23
GuildVaultWindow.UNLOCKS.VAULT4 = 33	-- Guild Vault 4 unlocks at Guild Rank 33

GuildVaultWindow.VaultPermission = {}
GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT1] = {}
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT1].view = SystemData.GuildPermissons.VAULT1_VIEW
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT1].give = SystemData.GuildPermissons.VAULT1_ADD_ITEM
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT1].take = SystemData.GuildPermissons.VAULT1_TAKE_ITEM

GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT2] = {}
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT2].view = SystemData.GuildPermissons.VAULT2_VIEW
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT2].give = SystemData.GuildPermissons.VAULT2_ADD_ITEM
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT2].take = SystemData.GuildPermissons.VAULT2_TAKE_ITEM

GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT3] = {}
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT3].view = SystemData.GuildPermissons.VAULT3_VIEW
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT3].give = SystemData.GuildPermissons.VAULT3_ADD_ITEM
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT3].take = SystemData.GuildPermissons.VAULT3_TAKE_ITEM

GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT4] = {}
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT4].view = SystemData.GuildPermissons.VAULT4_VIEW
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT4].give = SystemData.GuildPermissons.VAULT4_ADD_ITEM
	GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT4].take = SystemData.GuildPermissons.VAULT4_TAKE_ITEM

-- Guild Vault Commands. These must match the switch statement in war_interface::LuaSendGuildVaultCommand
GuildVaultWindow.COMMAND_MOVE_ITEM = 1
GuildVaultWindow.COMMAND_GIVE_COIN = 2
GuildVaultWindow.COMMAND_TAKE_COIN = 3
GuildVaultWindow.COMMAND_SLOT_LOCK = 4
GuildVaultWindow.COMMAND_SLOT_UNLOCK = 5
GuildVaultWindow.COMMAND_CLOSE = 6

GuildVaultWindow.dropPending = false

local function SetTabLabels()
	for index, TabIndex in ipairs(GuildVaultWindow.Tabs) do
		ButtonSetText(GuildVaultWindow.Tabs[index].name, GetGuildString(GuildVaultWindow.Tabs[index].label ) )
    end
end

----------------------------------------------------------------
-- GuildVaultWindow Functions
----------------------------------------------------------------
function GuildVaultWindow.Initialize()
	
	ActionButtonGroupSetNumButtons( "GuildVaultWindowSlots", 6, 10 )
	GuildVaultWindow.InitializeEditBoxes()

	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.INTERACT_DONE, "GuildVaultWindow.Hide")

	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.GUILD_INFO_UPDATED, "GuildVaultWindow.UpdateThingsWithPermissions")
	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.GUILD_MEMBER_UPDATED, "GuildVaultWindow.UpdateThingsWithPermissions")
	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.GUILD_PERMISSIONS_UPDATED, "GuildVaultWindow.UpdateThingsWithPermissions")

	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.INTERACT_GUILD_VAULT_OPEN, "GuildVaultWindow.OnGuildVaultOpened")
	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.INTERACT_GUILD_VAULT_CLOSED, "GuildVaultWindow.OnGuildVaultClosed")

	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.GUILD_VAULT_COIN_UPDATED, "GuildVaultWindow.UpdateMoneyInVault")
	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.GUILD_VAULT_ITEMS_UPDATED, "GuildVaultWindow.UpdateItemsInVault")

	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.GUILD_VAULT_SLOT_LOCKED, "GuildVaultWindow.SlotLocked")
	WindowRegisterEventHandler( "GuildVaultWindow", SystemData.Events.GUILD_VAULT_SLOT_UNLOCKED, "GuildVaultWindow.SlotUnlocked")


	-- Header text
	LabelSetText("GuildVaultWindowTitleBarText", GetGuildString(StringTables.Guild.LABEL_GUILD_VAULT))

	SetTabLabels()
	GuildVaultWindow.SelectTab(GuildVaultWindow.TABS_VAULT1)
	GuildVaultWindow.UpdateThingsWithPermissions()

	ButtonSetText("GuildVaultWindowDepositButton", GetGuildString(StringTables.Guild.BUTTON_GUILD_VAULT_DEPOSIT))
	ButtonSetText("GuildVaultWindowWithdrawButton", GetGuildString(StringTables.Guild.BUTTON_GUILD_VAULT_WITHDRAW))
end

function GuildVaultWindow.InitializeEditBoxes()
	WindowSetTintColor("GuildVaultWindowMoneyEditBoxGoldBackground",	0, 0, 0 )
	WindowSetTintColor("GuildVaultWindowMoneyEditBoxSilverBackground",	0, 0, 0 )
	WindowSetTintColor("GuildVaultWindowMoneyEditBoxBrassBackground",	0, 0, 0 )
end

function GuildVaultWindow.Shutdown()
end

function GuildVaultWindow.OnOpen()	-- Registered Event Trigger
	GuildVaultWindow.OnShown()
end

function GuildVaultWindow.OnClose()	-- Registered Event Trigger	(User closed the window)
	SendGuildVaultCommand(GuildVaultWindow.COMMAND_CLOSE, 0, 0, 0, 0, false)
	GuildVaultWindow.Hide()
end

function GuildVaultWindow.OnShown()
    WindowSetShowing( "GuildVaultWindow", true )
    EA_BackpackUtilsMediator.ShowBackpack()
end

function GuildVaultWindow.OnHidden()
    WindowUtils.OnHidden()
end

function GuildVaultWindow.Hide()
    WindowSetShowing( "GuildVaultWindow", false );	
end

function GuildVaultWindow.OnGuildVaultOpened(vaultDataTable)
	GuildVaultWindow.OnShown()

	GuildVaultWindow.vaultDataLockTable[GuildVaultWindow.TABS_VAULT1] = {}
	GuildVaultWindow.vaultDataLockTable[GuildVaultWindow.TABS_VAULT2] = {}
	GuildVaultWindow.vaultDataLockTable[GuildVaultWindow.TABS_VAULT3] = {}
	GuildVaultWindow.vaultDataLockTable[GuildVaultWindow.TABS_VAULT4] = {}

	GuildVaultWindow.vaultDataTable = DataUtils.CopyTable(vaultDataTable)

	GuildVaultWindow.SetMoneyInVault(GuildVaultWindow.vaultDataTable.MoneyInVault)
	GuildVaultWindow.UpdateThingsWithPermissions()
	GuildVaultWindow.UpdateVaultSlots(GuildVaultWindow.SelectedVault)
end

function GuildVaultWindow.OnGuildVaultClosed()
	GuildVaultWindow.vaultDataTable = {}
	GuildVaultWindow.Hide()
end

-----------------------------------------------------------
-- Tab Controls
-----------------------------------------------------------
function GuildVaultWindow.OnMouseOverTab()
    local windowIndex	= WindowGetId (SystemData.ActiveWindow.name)

	local statusNumber = GuildWindowTabAdmin.GetMemberTitleNumberByMemberName(GameData.Player.name)

	-- Customize the tooltip based on if the tab is enabled, disabled due to permission, or disabled due to low Guild Rank)
	local tooltipText = L""
	if windowIndex == GuildVaultWindow.TABS_VAULT1 then
		if GameData.Guild.m_GuildRank < GuildVaultWindow.UNLOCKS.VAULT1 then 
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipLocked)
		elseif GuildWindowTabAdmin.GetGuildCommandPermission(GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT1].view, statusNumber) == false then
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipDisabled)
		else
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipEnabled)
		end
	elseif windowIndex == GuildVaultWindow.TABS_VAULT2 then
		if GameData.Guild.m_GuildRank < GuildVaultWindow.UNLOCKS.VAULT2 then 
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipLocked)
		elseif GuildWindowTabAdmin.GetGuildCommandPermission(GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT2].view, statusNumber) == false then
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipDisabled)
		else
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipEnabled)
		end
	elseif windowIndex == GuildVaultWindow.TABS_VAULT3 then
		if GameData.Guild.m_GuildRank < GuildVaultWindow.UNLOCKS.VAULT3 then 
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipLocked)
		elseif GuildWindowTabAdmin.GetGuildCommandPermission(GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT3].view, statusNumber) == false then
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipDisabled)
		else
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipEnabled)
		end
	elseif windowIndex == GuildVaultWindow.TABS_VAULT4 then
		if GameData.Guild.m_GuildRank < GuildVaultWindow.UNLOCKS.VAULT4 then 
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipLocked)
		elseif GuildWindowTabAdmin.GetGuildCommandPermission(GuildVaultWindow.VaultPermission[GuildVaultWindow.TABS_VAULT4].view, statusNumber) == false then
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipDisabled)
		else
			tooltipText = GetGuildString( GuildVaultWindow.Tabs[windowIndex].tooltipEnabled)
		end
	end

    Tooltips.CreateTextOnlyTooltip (SystemData.ActiveWindow.name, nil)
    Tooltips.SetTooltipText (1, 1, tooltipText )
    Tooltips.SetTooltipColorDef (1, 1, Tooltips.COLOR_HEADING)	
    Tooltips.Finalize ()
    
    local anchor = { Point="top", RelativeTo=SystemData.MouseOverWindow.name, RelativePoint="bottom", XOffset=0, YOffset=-5 }
    Tooltips.AnchorTooltip (anchor)
    Tooltips.SetTooltipAlpha (1)
end

function GuildVaultWindow.SelectTab(tabID)
	GuildVaultWindow.SelectedVault = tabID

	if tabID <= GuildVaultWindow.TABS_VAULT4 and ButtonGetDisabledFlag("GuildVaultWindowTabsVault"..tabID) then
		return
	end

    for index, TabIndex in ipairs(GuildVaultWindow.Tabs) do
		ButtonSetPressedFlag( TabIndex.name, index == GuildVaultWindow.SelectedVault )
    end

	GuildVaultWindow.UpdateVaultSlots(GuildVaultWindow.SelectedVault)
end

function GuildVaultWindow.OnLButtonUpTab()
	GuildVaultWindow.SelectTab(WindowGetId (SystemData.ActiveWindow.name) )
end

-----------------------------------------------------------
-- Money Functions
-----------------------------------------------------------

function GuildVaultWindow.SetMoneyInVault(amount)
	MoneyFrame.FormatMoney ("GuildVaultWindowMoneyInVault", amount, MoneyFrame.SHOW_EMPTY_WINDOWS)
end

-----------------------------------------------------------
-- Permission Function
-----------------------------------------------------------
function GuildVaultWindow.UpdateThingsWithPermissions()

	local statusNumber = GuildWindowTabAdmin.GetMemberTitleNumberByMemberName(GameData.Player.name)

	-- Show or hide the Deposit and Withdraw buttons based on permissions. 
	local bShowDepositButton = GuildWindowTabAdmin.GetGuildCommandPermission(SystemData.GuildPermissons.VAULT_DEPOSIT, statusNumber)
	local bShowWithdrawButton = GuildWindowTabAdmin.GetGuildCommandPermission(SystemData.GuildPermissons.VAULT_WITHDRAW, statusNumber)
	WindowSetShowing("GuildVaultWindowDepositButton", bShowDepositButton)
	WindowSetShowing("GuildVaultWindowWithdrawButton", bShowWithdrawButton)

	WindowSetShowing("GuildVaultWindowMoney", bShowDepositButton or bShowWithdrawButton)
	
	-- Disable vault tabs that the guild doesn't have unlocked (nil) or the user doesn't have access to (num slots = 0)
	local firstViewableVault = false
	for vaultIndex = 1, GuildVaultWindow.MAX_VAULTS
	do
        local vaultLocked = GuildVaultWindow.vaultDataTable[vaultIndex] == nil
        local playerDoesNotHaveAccess = true
        if not vaultLocked
        then
            playerDoesNotHaveAccess = GuildVaultWindow.vaultDataTable[vaultIndex].NumberOfSlots == 0
        end
        local disable = vaultLocked or playerDoesNotHaveAccess
        
        ButtonSetDisabledFlag( "GuildVaultWindowTabsVault"..vaultIndex, disable )
        
        -- Remember the first valid vault, so we can switch to it below if we need to
        if not disable and not firstViewableVault
        then
            firstViewableVault = vaultIndex
        end
	end

    -- If the user is looking at a Vault Tab for which permission is no longer granted, then switch to the first tab they do have access to.
    -- Note: If the user has access to none of the vaults, and no access to deposit/withddraw, the server will close the vault window.
    if ButtonGetDisabledFlag( "GuildVaultWindowTabsVault"..GuildVaultWindow.SelectedVault )
    then
        if firstViewableVault
        then
            GuildVaultWindow.SelectTab( firstViewableVault )
        else
            -- If we get here and the selected vault tab is disabled, we don't have permission to view
            -- any vault, but we can deposit money. We'll leave the item slots alone so the window
            -- doesn't look strange, but unset the pressed flag of the current tab, as we don't
            -- have a pressed disabled state
            ButtonSetPressedFlag( "GuildVaultWindowTabsVault"..GuildVaultWindow.SelectedVault, false )
        end
    else
        ButtonSetPressedFlag( "GuildVaultWindowTabsVault"..GuildVaultWindow.SelectedVault, true )
    end

end

function GuildVaultWindow.OnMouseOverVaultSlot(slot, flags)
	local itemData = GuildVaultWindow.GetItemDataFromVaultSlot(GuildVaultWindow.SelectedVault, slot)

	if itemData ~= nil and itemData.id ~= nil and itemData.id > 0 then
		Tooltips.CreateItemTooltip (itemData, SystemData.ActiveWindow.name.."Button"..slot, Tooltips.ANCHOR_WINDOW_BOTTOM)
    end
end

function GuildVaultWindow.OnMouseOverVaultSlotEnd()
end

-----------------------------------------------------------
-- Command Functions
-----------------------------------------------------------

function GuildVaultWindow.OnLButtonUpDepositButton()
	local money = tonumber(GuildVaultWindowMoneyEditBoxGold.Text) * 10000 + 
					tonumber(GuildVaultWindowMoneyEditBoxSilver.Text) * 100 + 
					tonumber(GuildVaultWindowMoneyEditBoxBrass.Text)
	SendGuildVaultCommand(GuildVaultWindow.COMMAND_GIVE_COIN, money, 0, 0, 0, false)
end

function GuildVaultWindow.OnLButtonUpWithdrawButton()
	local money = tonumber(GuildVaultWindowMoneyEditBoxGold.Text) * 10000 + 
					tonumber(GuildVaultWindowMoneyEditBoxSilver.Text) * 100 + 
					tonumber(GuildVaultWindowMoneyEditBoxBrass.Text)
	SendGuildVaultCommand(GuildVaultWindow.COMMAND_TAKE_COIN, money, 0, 0, 0, false)
end

function GuildVaultWindow.IsVaultOpen()
	if WindowGetShowing("GuildVaultWindow") and GuildVaultWindow.SelectedVault >= GuildVaultWindow.TABS_VAULT1 and GuildVaultWindow.SelectedVault <= GuildVaultWindow.TABS_VAULT4 then 
		return true 
	end

	return false
end

-----------------------------------------------------------
-- Button & Item Handlers 
-----------------------------------------------------------

function GuildVaultWindow.SetItemInSlot(vaultID, slot, itemData)
	local vaultData = GuildVaultWindow.vaultDataTable[vaultID]
	
	--if itemData and itemData.id and itemData.id > 0 then
	if itemData == nil or itemData.id == nil or itemData.id == 0 then

        if vaultData
        then
            vaultData.itemsAttached[slot] = nil
        end

		-- Only update the icon if the update is for the same vault we're currently looking at. 
		-- If we don't do this, an item deleted from Vault X could remove the icon in the same slot from the currently selected vault.
		if vaultID == GuildVaultWindow.SelectedVault then
			ActionButtonGroupSetIcon( "GuildVaultWindowSlots", slot, 0 )
			ActionButtonGroupSetText( "GuildVaultWindowSlots", slot, L"" )
			--ActionButtonGroupSetTimer( "GuildVaultWindowSlots", buttonID, 0, 0 )        
			--ActionButtonGroupSetGameActionData( "GuildVaultWindowSlots", buttonID, 0, 0, L"")
		end
		
		return
	end

	-- Item
	vaultData.itemsAttached[slot] = DataUtils.CopyTable(itemData)

	-- Only update the icon if the update is for the same vault we're currently looking at. 
	-- If we don't do this, an item added into Vault X could add the icon in the same slot into the currently selected vault.
	if vaultID == GuildVaultWindow.SelectedVault then
		ActionButtonGroupSetIcon( "GuildVaultWindowSlots", slot, 0 )
		ActionButtonGroupSetText( "GuildVaultWindowSlots", slot, L"" )
		--ActionButtonGroupSetTimer( "GuildVaultWindowSlots", buttonID, 0, 0 )        
		--ActionButtonGroupSetGameActionData( "GuildVaultWindowSlots", buttonID, 0, 0, L"")

		-- Icon
		ActionButtonGroupSetIcon( "GuildVaultWindowSlots", slot, itemData.iconNum )

		-- Count
		local stackCountText = L""
		if itemData.stackCount > 1 then
			stackCountText = L""..itemData.stackCount
		end
		ActionButtonGroupSetText( "GuildVaultWindowSlots", slot, stackCountText )

		-- Cooldown Timer
		--local cooldownTimeLeft, totalCooldownTime = EA_Window_Backpack.GetItemCooldownTimers( itemData )
		--if( cooldownTimeLeft ~= nil )
		--then
		--	ActionButtonGroupSetTimer( buttonGroupName, buttonIndex, totalCooldownTime, cooldownTimeLeft )
		--else    
		--	ActionButtonGroupSetTimer( buttonGroupName, buttonIndex, 0, 0 ) 
		--end

	end
end

function GuildVaultWindow.GetItemDataFromVaultSlot(vaultID, slotNumber)
	if GuildVaultWindow.vaultDataTable[vaultID] ~= nil and 
		GuildVaultWindow.vaultDataTable[vaultID].itemsAttached ~= nil and
		GuildVaultWindow.vaultDataTable[vaultID].itemsAttached[slotNumber] ~= nil
	then
		return GuildVaultWindow.vaultDataTable[vaultID].itemsAttached[slotNumber]
	end

	return nil
end

function GuildVaultWindow.IsSlotLocked(source, sourceSlot)
	for slotNumber, slot in pairs( GuildVaultWindow.vaultDataLockTable[source] ) do
		if slot == sourceSlot then
			return true
		end
	end
	return false
end

function GuildVaultWindow.UpdateVaultSlots(vaultID)
	-- This function refreshes all the slots for the passed in Vault Number.
	-- (No need to update all slots for all vaults since we only show the slots for 1 vault at a time, and each
	-- time we switch vaults, we refresh all slots for the newly selected tab)
	local itemData = nil

    local clearVault = false
	if GuildVaultWindow.vaultDataTable == nil or GuildVaultWindow.vaultDataTable[vaultID] == nil then 
        clearVault = true
	end

	for i=1, GuildVaultWindow.MAX_SLOTS do
		itemData = nil

		if  not clearVault
            and GuildVaultWindow.vaultDataTable[vaultID].itemsAttached ~= nil
            and GuildVaultWindow.vaultDataTable[vaultID].itemsAttached[i] ~= nil
        then
			itemData = GuildVaultWindow.vaultDataTable[vaultID].itemsAttached[i]
		end
		
		-- Update the slot's icon
		GuildVaultWindow.SetItemInSlot(vaultID, i, itemData)

		-- Update the slot's tint
		if GuildVaultWindow.IsSlotLocked(vaultID, i) then
			ActionButtonGroupSetTintColor("GuildVaultWindowSlots", i, 128, 128, 128)
		else
			ActionButtonGroupSetTintColor("GuildVaultWindowSlots", i, 255, 255, 255)
		end

	end
end

function GuildVaultWindow.OnLButtonDownVaultSlot(buttonIndex, flags)

	-- We can do one of three things... 
	--  1) If there's no item in the slot and the cursor doesn't have an item on it, do nothing.
	--	2) If the cursor already has an item attached, and the slot is empty, then place it.
	--	3) If the cursor doesn't have an item attached, pick up the item in the slot.

	-- 1) If there's no item in the slot and the cursor doesn't have an item on it, do nothing.
	if (Cursor.IconOnCursor() == false)and GuildVaultWindow.GetItemDataFromVaultSlot(GuildVaultWindow.SelectedVault, buttonIndex) == nil then
		return
	end

	--	2) If the cursor already has an item attached, drop it.
    if Cursor.IconOnCursor() then

		-- Verify user has permission to place an item in this guild vault.
		local statusNumber = GuildWindowTabAdmin.GetMemberTitleNumberByMemberName(GameData.Player.name)
		local bGiveVault = GuildWindowTabAdmin.GetGuildCommandPermission(GuildVaultWindow.VaultPermission[GuildVaultWindow.SelectedVault].give, statusNumber)
		if bGiveVault == false then
			local errorText = GetFormatStringFromTable( "GuildStrings", StringTables.Guild.ERROR_GUILD_VAULT_NO_GIVE_PERMISSION, {GuildVaultWindow.SelectedVault} ) 
			EA_ChatWindow.Print(errorText, SystemData.ChatLogFilters.SAY) 
			return
		end

        -- If we're dropping the Item onto the same slot we picked it up from, just clear the cursor
		if( Cursor.Data.Source >= Cursor.SOURCE_GUILD_VAULT1 and		-- Verify that the source slot
			Cursor.Data.Source <= Cursor.SOURCE_GUILD_VAULT4 and		--		is a vault slot
			Cursor.Data.Source == GuildVaultWindow.SelectedVault and	-- Verify the source and dest vaults are the same
			Cursor.Data.SourceSlot == buttonIndex )						-- Verify the source slot is the same as the selected slot
		then
			SendGuildVaultCommand(GuildVaultWindow.COMMAND_SLOT_UNLOCK, GuildVaultWindow.SelectedVault, buttonIndex, 0, 0, false)
            Cursor.Clear()
        else
			local itemData = GuildVaultWindow.GetItemDataFromVaultSlot(GuildVaultWindow.SelectedVault, buttonIndex)

			-- If the slot is clear, drop the item into it.
			if itemData == nil then
				-- If the source is the backpack, the server is expecting a sourceID of 0, otherwise it expects the source to be the vault#.
                local backpackType = EA_BackpackUtilsMediator.GetCurrentBackpackType()
                local currentCursor = EA_BackpackUtilsMediator.GetCursorForBackpack( backpackType )
				if Cursor.Data.Source == currentCursor
                then
                    local backpackType = EA_BackpackUtilsMediator.GetCurrentBackpackType() + GuildVaultWindow.TABS_VAULT4
					SendGuildVaultCommand(GuildVaultWindow.COMMAND_MOVE_ITEM, backpackType, Cursor.Data.SourceSlot, GuildVaultWindow.SelectedVault, buttonIndex, false)
				else--if Cursor.Data.Source >= Cursor.SOURCE_GUILD_VAULT1 and Cursor.Data.Source <= Cursor.SOURCE_GUILD_VAULT4 then
					SendGuildVaultCommand(GuildVaultWindow.COMMAND_MOVE_ITEM, Cursor.Data.Source - Cursor.SOURCE_GUILD_VAULT1 +1, Cursor.Data.SourceSlot, GuildVaultWindow.SelectedVault, buttonIndex, false)
				end
				Cursor.Clear()
				return
			end
		end
		return
    end

	--	3) If the cursor doesn't have an item attached, and the slot isn't locked, pick up the item in the slot.
	if (GuildVaultWindow.IsSlotLocked(GuildVaultWindow.SelectedVault, buttonIndex) == false) then
		-- Verify user has permission to place an item in this guild vault.
		local statusNumber = GuildWindowTabAdmin.GetMemberTitleNumberByMemberName(GameData.Player.name)
		local bTakeVault = GuildWindowTabAdmin.GetGuildCommandPermission(GuildVaultWindow.VaultPermission[GuildVaultWindow.SelectedVault].take, statusNumber)
		if bTakeVault == false then
			local errorText = GetFormatStringFromTable( "GuildStrings", StringTables.Guild.ERROR_GUILD_VAULT_NO_TAKE_PERMISSION, {GuildVaultWindow.SelectedVault} ) 
			EA_ChatWindow.Print(errorText, SystemData.ChatLogFilters.SAY) 
			return
		end

		local itemData = GuildVaultWindow.GetItemDataFromVaultSlot(GuildVaultWindow.SelectedVault, buttonIndex)
		if itemData ~= nil then

			-- NOTE: We're ignoring stackable items for now. (Splitting up a stacked item from within the Vault is not server supported yet.
			-- If the Shift key is pressed while cilcking on a stacked item, then only pick up some of the stack
			--if ( (flags == SystemData.ButtonFlags.SHIFT) and itemData.stackCount > 1 ) then
			--    ItemStackingWindow.Show(GuildVaultWindow.VaultSource[GuildVaultWindow.SelectedVault], buttonIndex)
			--else
				SendGuildVaultCommand(GuildVaultWindow.COMMAND_SLOT_LOCK, GuildVaultWindow.SelectedVault, buttonIndex, 0, 0, false)
				Cursor.PickUp( GuildVaultWindow.VaultSource[GuildVaultWindow.SelectedVault], buttonIndex, itemData.uniqueID, itemData.iconNum, true)
			--end

			--GuildVaultWindow.dropPending = false
			return
		end
	end
end

function GuildVaultWindow.OnLButtonUpVaultSlot(buttonIndex, flags)
	-- In order to support Drag & Drop, we should only respond to this event if all the following cases are true
	-- 1) There is already an item on the cursor
	-- 2) The sourceslot is not the same as the butotnIndex (otherwise, we'll always be pickuping up item in LbuttonDown, but then dropping it here)

	if Cursor.IconOnCursor() and Cursor.Data.SourceSlot ~= buttonIndex then 
		GuildVaultWindow.OnLButtonDownVaultSlot(buttonIndex, flags)
	end
end

-- If the user R-clicks to clear the cursor outside the guild vault, Cursor.OnRButtonDownProcessed() handles the cursor clear, 
-- but if the source is the Guild Vault, it also calls this function.
function GuildVaultWindow.ClearUnlock(source, sourceSlot)
	SendGuildVaultCommand(GuildVaultWindow.COMMAND_SLOT_UNLOCK, source-Cursor.SOURCE_GUILD_VAULT1+1, sourceSlot, 0, 0, false)
end

function GuildVaultWindow.OnRButtonUpVaultSlot(buttonIndex)
	-- If the user already has something on the cursor, do nothing.
	if Cursor.IconOnCursor() then
		return
	end

	local statusNumber = GuildWindowTabAdmin.GetMemberTitleNumberByMemberName(GameData.Player.name)
	local bTakeVault = GuildWindowTabAdmin.GetGuildCommandPermission(GuildVaultWindow.VaultPermission[GuildVaultWindow.SelectedVault].take, statusNumber)
	if bTakeVault == false then
		local errorText = GetFormatStringFromTable( "GuildStrings", StringTables.Guild.ERROR_GUILD_VAULT_NO_TAKE_PERMISSION, {GuildVaultWindow.SelectedVault} ) 
		EA_ChatWindow.Print(errorText, SystemData.ChatLogFilters.SAY) 
		return
	end

	local itemData = GuildVaultWindow.GetItemDataFromVaultSlot(GuildVaultWindow.SelectedVault, buttonIndex)

	if itemData ~= nil and itemData.id ~= nil and itemData.id >0 then
		-- Move the item from the Selected Vault to the player's backpack. 
		-- Note that the 4th param is 0, which tells the server that the dest is the player's backpack.
		SendGuildVaultCommand(GuildVaultWindow.COMMAND_MOVE_ITEM, GuildVaultWindow.SelectedVault, buttonIndex, 0, GameData.Inventory.FIRST_AVAILABLE_INVENTORY_SLOT, true)
	end
end

-- This function handles the Guild Vault command to move an Item from the Guild Vault to the player's Backpack.
-- It's called from EA_Window_Backpack.EquipmentLButtonDown in BackpackUtils.lua. 
function GuildVaultWindow.MoveItemFromGuildVaultToBackpack(vaultNumber, backpackSlot, flags, backpackType)
	-- Special: Server expects a source ID of 0 for the backpack.
    local backpack = backpackType + GuildVaultWindow.TABS_VAULT4
	SendGuildVaultCommand(GuildVaultWindow.COMMAND_MOVE_ITEM, vaultNumber, Cursor.Data.SourceSlot, backpack, backpackSlot, false)
	Cursor.Clear()
end

function GuildVaultWindow.OnRButtonUpBackpack(buttonIndex)
	-- Move the item from the player's backpack to the selected Guild Vault.
	-- Note that the 2nd param is 0, which tells the server that the source location is the player's backpack.
	-- Don't worry about offsetting the backpack slot#, that'll happen on the C side.
	-- Ensure the user has write permission to this vault
	local statusNumber = GuildWindowTabAdmin.GetMemberTitleNumberByMemberName(GameData.Player.name)
	local bGiveVault = GuildWindowTabAdmin.GetGuildCommandPermission(GuildVaultWindow.VaultPermission[GuildVaultWindow.SelectedVault].give, statusNumber)

	if bGiveVault
    then
        local backpackType = EA_BackpackUtilsMediator.GetCurrentBackpackType() + GuildVaultWindow.TABS_VAULT4
		SendGuildVaultCommand(GuildVaultWindow.COMMAND_MOVE_ITEM, backpackType, buttonIndex, GuildVaultWindow.SelectedVault, GameData.Inventory.FIRST_AVAILABLE_GUILD_VAULT_SLOT, true)
	else
		local errorText = GetFormatStringFromTable( "GuildStrings", StringTables.Guild.ERROR_GUILD_VAULT_NO_GIVE_PERMISSION, {GuildVaultWindow.SelectedVault} ) 
		EA_ChatWindow.Print(errorText, SystemData.ChatLogFilters.SAY) 
	end
end

function GuildVaultWindow.UpdateMoneyInVault(amount)
	GuildVaultWindow.vaultDataTable.MoneyInVault = amount
	GuildVaultWindow.SetMoneyInVault(amount)
end

-- LUA Script param includes a table of vaults and items that have been changed. This is NOT a new list of all items in all vaults!
function GuildVaultWindow.UpdateItemsInVault(vaultData)
-- The Parameter structure looks like this:
-- vaultData									This table contains all the vaults that have changed.
--		vaultData[vault#]						This table contains contains all the changes to this vault.
--			vaultData[vault#].itemsUpdated		This table contains all the items that have changed for this vault. The Index is the slot#.
--				vaultData.itemsUpdated[slot#]	This table contains the itemData.
	for vaultIndex, data in pairs(vaultData) do
		for slotIndex, itemData in pairs (data.itemsUpdated) do
			GuildVaultWindow.SetItemInSlot(vaultIndex, slotIndex, itemData)
		end
	end
end

function GuildVaultWindow.OnMouseOverDepositButton()
    Tooltips.CreateTextOnlyTooltip (SystemData.MouseOverWindow.name, nil)
    Tooltips.SetTooltipText (1, 1, GetGuildString(StringTables.Guild.TOOLTIP_GUILD_VAULT_DEPOSIT_BUTTON) )
    Tooltips.SetTooltipColorDef (1, 1, Tooltips.COLOR_HEADING)
    Tooltips.Finalize ()
    
    Tooltips.AnchorTooltip( Tooltips.ANCHOR_WINDOW_BOTTOM )
end

function GuildVaultWindow.OnMouseOverWithdrawButton()
    Tooltips.CreateTextOnlyTooltip (SystemData.MouseOverWindow.name, nil)
    Tooltips.SetTooltipText (1, 1, GetGuildString(StringTables.Guild.TOOLTIP_GUILD_VAULT_WITHDRAW_BUTTON) )
    Tooltips.SetTooltipColorDef (1, 1, Tooltips.COLOR_HEADING)	
    Tooltips.Finalize ()
    
    Tooltips.AnchorTooltip( Tooltips.ANCHOR_WINDOW_BOTTOM )
end

function GuildVaultWindow.SlotLocked(memberID, source, sourceSlot)
	local itemData = GuildVaultWindow.GetItemDataFromVaultSlot(source, sourceSlot)
	local vaultLockedList = GuildVaultWindow.vaultDataLockTable[source]
	-- Use the slotID as an index to the memberID. This tells us 2 things: That the slot is locked, and who locked it.
	table.insert(GuildVaultWindow.vaultDataLockTable[source], sourceSlot)

	-- If the user didn't lock the slot but has the item on their cursor, clear their cursor.
	local localMemberID = GuildWindowTabRoster.GetMemberID()
	if memberID ~= localMemberID and Cursor.Data ~= nil and Cursor.Data.SourceSlot == source and Cursor.Data.SourceSlot == sourceSlot then
		Cursor.Clear()
	end

	-- Grey out the slot that's been locked and if the memberID matches you, pickup the item.
	-- its possibel to pick up an item in V2 and then quickly click V1, thereby greying out the V2 slot in V1. So verify the source.
	if GuildVaultWindow.SelectedVault == source then 
		ActionButtonGroupSetTintColor("GuildVaultWindowSlots", sourceSlot, 128, 128, 128)
	end
end

function GuildVaultWindow.SlotUnlocked(memberID, source, sourceSlot)
	-- Add the slotId to our list of locked slots for the source vault
	if GuildVaultWindow.vaultDataLockTable[source] ~= nil then 
		table.remove(GuildVaultWindow.vaultDataLockTable[source], sourceSlot)
	end

	local itemData = GuildVaultWindow.GetItemDataFromVaultSlot(source, sourceSlot)

	-- If the slot was owned by the current user, clear their cursor.
	for index, memberData in ipairs(GuildWindowTabRoster.memberListData) do
		if memberData.memberID == memberID and itemData ~= nil and itemData.id ~= nil and itemData.id > 0 then
			Cursor.Clear()
			break
		end
	end

	-- Ungrey the locked slot if we're looking at the vault whose's slot is getting unlocked.
	if source == GuildVaultWindow.SelectedVault then
		ActionButtonGroupSetTintColor("GuildVaultWindowSlots", sourceSlot, 255, 255, 255)
	end
end
